package net.infamily.web;

import net.infamily.logic.UserLogic;
import net.infamily.model.User;

import org.apache.wicket.Request;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;



public class MyWebSession extends AuthenticatedWebSession {
	private static final long serialVersionUID = 1L;
	private static final String USER_ATTRIBUTE = MyWebSession.class
			.getName() + ".USER_ATTRIBUTE";

	public MyWebSession(Request request) {
		super(request);
	}

	@Override
	public boolean authenticate(String username, String password) {
		User user = getLoginLogic().login(username, password);
		if (user != null) {
			setAttribute(USER_ATTRIBUTE, user);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Roles getRoles() {
		User user = getUser();
		if (user == null) {
			return null;
		} else if (user.getAdminFlag()) {
			return new Roles(new String[] { Roles.ADMIN, Roles.USER });
		} else {
			return new Roles(Roles.USER);
		}
	}

	public User getUser() {
		return (User) getAttribute(USER_ATTRIBUTE);
	}

	public UserLogic getLoginLogic() {
		MyWebApp app = (MyWebApp) getApplication();
		return app.getLoginLogic();
	}
}
